import { AlipayOutlined, AppstoreOutlined, CreditCardOutlined, DollarCircleOutlined, FlagOutlined, MoneyCollectOutlined, TransactionOutlined, WalletOutlined, WechatOutlined } from '@ant-design/icons';
import { Divider, Form, FormInstance, Input, message, Modal, Select, Tabs } from 'antd';
import moment, { Moment } from 'moment';
import React, { useCallback, useContext, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Action } from 'redux';
import { BudgetItem } from '../../interface/budgetData';
import { DataRowResult } from '../../interface/response';
import { DarkModeSelector } from '../../redux/Global/selector';
import { ActionProps } from '../../redux/type';
import { PostNewBudgetURL, ReqtHeader } from '../../RequestURL';
import FormatNumber from '../../util/formatNumber';
import { HeaderContext } from '../Header';
import { RecordTypeExpenses, RecordTypeIncome } from './RecordList/RecordItem';

interface AddRecordModalProps
{
    isOpen: boolean;
    IsOpenAddBudgetModalContext: React.Context<HeaderContext>;
}

export default function AddRecordModal(props: AddRecordModalProps)
{
    const {
        setIsOpenAddBudgetModal,
        defaultTabIndex,
    } = useContext(props.IsOpenAddBudgetModalContext);

    const formIns = useRef<FormInstance>(null);

    return (
        <Modal centered visible={props.isOpen}
            onCancel={e =>
            {
                setIsOpenAddBudgetModal(false);
            }}
            onOk={e =>
            {
                formIns.current!.submit();
            }}
            okText='确定' cancelText='取消'
        >
            <Tabs defaultActiveKey={defaultTabIndex}>
                <Tabs.TabPane key='EXPENSES' tab={
                    <span>
                        <TransactionOutlined />
                        支出
                    </span>
                }>
                    <RecordModalFormPanel budgetType='EXPENSES' formIns={formIns}
                        setIsOpenAddBudgetModal={setIsOpenAddBudgetModal} />
                </Tabs.TabPane>
                <Tabs.TabPane key='INCOME' tab={
                    <span>
                        <MoneyCollectOutlined />
                        收入
                    </span>
                }>
                    <RecordModalFormPanel budgetType='INCOME' formIns={formIns}
                        setIsOpenAddBudgetModal={setIsOpenAddBudgetModal} />

                </Tabs.TabPane>
            </Tabs>
        </Modal>
    );
}


interface RecordModalFormPanelProps
{
    budgetType: 'INCOME' | 'EXPENSES';
    formIns: React.Ref<FormInstance>;
    setIsOpenAddBudgetModal: Function;
}
export function RecordModalFormPanel(props: RecordModalFormPanelProps)
{
    const darkMode = useSelector(DarkModeSelector);

    const dispatch = useDispatch();

    const PostNewBudget = useCallback(async (data: BudgetItem): Promise<DataRowResult[]> =>
    {
        let res = await fetch(PostNewBudgetURL, {
            method: "POST",
            headers: ReqtHeader.JSON,
            body: JSON.stringify(data)
        });
        return await res.json() as DataRowResult[];
    }, []);
    return (
        <Form ref={props.formIns} onFinish={async (e: BudgetItem) =>
        {
            if (e.budget_amount)
            {
                e.budget_amount = Number(e.budget_amount).toFixed(2);
            }
            e.budget_type = props.budgetType;
            e.budget_date = new Date();

            const res: DataRowResult[] = await PostNewBudget(e);

            if (res[0].affectedRows === 1 && res[1].affectedRows === 1) message.success('添加成功');
            else message.error('错误,请重试');

            //Async Fetch Current Month BudgetList
            dispatch<ActionProps<string, Moment[]>>({
                type: "GetBudgetListData",
                payload: [
                    moment().startOf('month'),
                    moment().endOf('month'),
                ],
            });
            dispatch<Action>({ type: "SelectBudgetExhibitData" });
            props.setIsOpenAddBudgetModal(false);
        }}>
            <Form.Item
                name='budget_amount'
                initialValue={FormatNumber('0')}
            >
                <input className='BudgetAmountInput' type='text'
                    autoComplete='off'
                    style={{
                        borderBottom: props.budgetType === 'EXPENSES' ? "3px solid #f5222d" : '3px solid #52c41a',
                        color: props.budgetType === 'EXPENSES' ? '#f5222d' : "#52c41a",
                        backgroundColor: darkMode ? '#1f1f1f' : '',
                    }}
                    onFocus={e =>
                    {
                        e.target.select();
                    }}
                />
            </Form.Item>
            <Form.Item
                label={
                    <span>
                        <AppstoreOutlined />
                        &nbsp;
                        分类
                    </span>
                }
                initialValue={props.budgetType === 'EXPENSES' ? "早午晚餐" : '工资收入'}
                name='budget_category'
            >
                <Select size='large' bordered={false}>
                    {
                        props.budgetType === 'EXPENSES'
                            ? [...RecordTypeExpenses.keys()].map((v: string) =>
                            (
                                <Select.OptGroup key={v} title={v}>
                                    {
                                        RecordTypeExpenses.get(v)?.map(item => (
                                            <Select.Option key={item.type}>
                                                {item.icon}
                                                &nbsp;&nbsp;
                                                {item.type}
                                            </Select.Option>
                                        ))
                                    }
                                </Select.OptGroup>
                            ))
                            : [...RecordTypeIncome.keys()].map((v: string) =>
                            (
                                <Select.OptGroup key={v} title={v}>
                                    {
                                        RecordTypeIncome.get(v)?.map(item => (
                                            <Select.Option key={item.type}>
                                                {item.icon}
                                                &nbsp;&nbsp;
                                                {item.type}
                                            </Select.Option>
                                        ))
                                    }
                                </Select.OptGroup>
                            ))
                    }
                </Select>
            </Form.Item>
            <Divider />
            <Form.Item
                label={
                    <span>
                        <WalletOutlined />
                        &nbsp;
                        账户
                    </span>
                }
                name='budget_way'
                initialValue={'支付宝'}
            >
                <Select size='large' bordered={false}>
                    <Select.Option value='支付宝'><AlipayOutlined />&nbsp;&nbsp;支付宝</Select.Option>
                    <Select.Option value='微信'><WechatOutlined />&nbsp;&nbsp;微信</Select.Option>
                    <Select.Option value='银行卡'><CreditCardOutlined />&nbsp;&nbsp;银行卡</Select.Option>
                    <Select.Option value='现金'><DollarCircleOutlined />&nbsp;&nbsp;现金</Select.Option>
                </Select>
            </Form.Item>
            <Divider />
            <Form.Item
                name='budget_memo'
                initialValue={''}
                label={
                    <span>
                        <FlagOutlined />
                        &nbsp;
                        备注
                    </span>
                }>
                <Input size='large' placeholder='...' />
            </Form.Item>
        </Form>
    );
}
